import _ from 'lodash'
import {constantRoutes} from '@/router'
import {menu, permission} from '@/mockData/index.js'

const modules = import.meta.glob('../../views/**/index.vue')
const Layout = () => import('@/layout/index.vue')

// 创建路由菜单
const filterAsyncRoutes = (menuList) => {
    const res = []
    menuList.forEach((item) => {
        const reg = new RegExp('/auth/global')
        const reg1 = new RegExp('/auth/auth')
        const reg2 = new RegExp('/auth/log/')
        const reg3 = new RegExp('/tmms')
        item.resourceUrl = item.resourceUrl.replace(reg, '/auth')
        item.resourceUrl = item.resourceUrl.replace(reg1, '/auth')
        item.resourceUrl = item.resourceUrl.replace(reg2, '/auth/')
        item.resourceUrl = item.resourceUrl.replace(reg3, '')

        item.resourceCode = item.resourceCode.replace(new RegExp('/tmms'), '')
        item.resourceCode = item.resourceCode.replace(new RegExp('/auth'), '')

        const _name = item.resourceUrl.replace('/', '').replace(/\//g, '_')
        let _component = () => import('@/views/404.vue')
        if (modules[`../../views${item.resourceCode}/index.vue`]) {
            _component = modules[`../../views${item.resourceCode}/index.vue`]
        }
        let menu = {
            path: item.resourceUrl,
            component: item.subId === 0 ? Layout : _component,
            name: _name,
            meta: {
                title: item.resourceName,
                id: item.mainId,
                affix: item.affix,
                icon: item.subId === 0 ? item.resourceIcon : null,
                noCache: false
            }
        }
        if (item.listSubMenu && item.subId === 0) {
            menu.children = filterAsyncRoutes(item.listSubMenu)
        }
        res.push(menu)
    })
    return res
}
export const usePermissionStore = defineStore('permission', () => {
    const userStore = useUserStore()
    const state = reactive({
        routes: [],
        isGetMenu: false,
        listPermission: []
    })
    // 获取路由
    const generateRoutes = () => {
        return new Promise((resolve) => {
            const loadMenuData = []
            const data = {
                listMainMenu: menu,
                listPermission: permission
            }
            Object.assign(loadMenuData, data)
            state.listPermission = loadMenuData.listPermission
            state.isGetMenu = true
            let accessedRoutes = filterAsyncRoutes(loadMenuData.listMainMenu)
            state.routes = constantRoutes.concat(accessedRoutes)
            resolve(accessedRoutes)

            // 先查询后台并返回左侧菜单数据并把数据添加到路由
            // getAuthMenu(store.getters.id, getToken(), obj.menu, obj.search)
            /*request({
             url: '/menu',
             method: 'get',
             params: {userid: userStore.userId, lowFrequencyHidden: true, appId: 4} // 用户id 低频隐藏 appId
             }).then((response) => {
             let data = response
             if (response.code !== 200) {
             Emessage('error', '菜单数据加载异常。')
             } else {
             // data = response.data.result
             data = {
             listMainMenu: menu,
             listPermission: permission
             }
             Object.assign(loadMenuData, data)
             state.listPermission = loadMenuData.listPermission
             state.isGetMenu = true
             let accessedRoutes = filterAsyncRoutes(loadMenuData.listMainMenu)
             // accessedRoutes[3].children.push({
             //     path: '/operationLog/workerExport',
             //     component: modules[`../../views/operationLog/workerExport/index.vue`],
             //     children: [],
             //     name: 'operationLog_workerExport',
             //     meta: {title: '😂工作成果导出', id: null, icon: null},
             //     hidden: false
             // })
             state.routes = constantRoutes.concat(accessedRoutes)
             resolve(accessedRoutes)
             }
             }).catch((error) => {
             console.error(error)
             })
             */

        })
    }

    return {
        generateRoutes,
        ...toRefs(state)
    }
})
